package ph.com.gs3.formalistics.fragments.views;

import java.util.ArrayList;
import java.util.List;

import ph.com.gs3.formalistics.R;
import ph.com.gs3.formalistics.dummylist.DummyDocumentList;
import ph.com.gs3.formalistics.interfaces.view.UserActionListItemInterface;
import ph.com.gs3.formalistics.model.valueobjects.application.FormStub;
import ph.com.gs3.formalistics.utilities.FLLogger;
import ph.com.gs3.formalistics.utilities.ViewGroupUtils;
import android.R.color;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.ActionBar.TabListener;
import android.app.Activity;
import android.app.FragmentTransaction;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;

public class MainViewFragment extends Fragment {

	public static final String TAG = MainViewFragment.class.getSimpleName();

	// ========================================================================
	// Fields

	private List<Fragment> viewFragments;
	private List<ImageView> tabIcons;

	private List<FormStub> formFilterSelection;

	private FormStub currentlySelectedFormFilter;

	private MainViewActivityActionListener listener;

	// ========================================================================
	// Fragments

	private DocumentListViewFragment homeViewFragment;
	private DocumentListViewFragment myWorkViewFragment;
	private DocumentListViewFragment myDocumentsViewFragment;
	private DocumentListViewFragment starredDocumentsViewFragment;
	private DocumentListViewFragment outboxDocumentViewFragment;

	// ========================================================================
	// View Components

	private ViewPager vpMainViewPager;
	private ActionBar abMainActionBar;
	private Spinner spFormFilter;
	private TextView tvMessage;

	private ArrayAdapter<FormStub> formfilterAdapter;

	public static MainViewFragment createInstance(
			List<FormStub> initialFormFilterSelection) {
		MainViewFragment newInstance = new MainViewFragment();
		if (initialFormFilterSelection != null) {
			newInstance.addFormFilters(initialFormFilterSelection);
		}
		return newInstance;
	}

	public MainViewFragment() {
		resetFormFilterSelection();
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		try {
			listener = (MainViewActivityActionListener) activity;
		} catch (ClassCastException e) {
			throw new ClassCastException(activity.toString()
					+ " must implement MainViewActivityActionListener");
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_main, container,
				false);

		initializeViewComponents(rootView);

		return rootView;
	}

	private void resetFormFilterSelection() {

		if (formFilterSelection == null) {
			formFilterSelection = new ArrayList<FormStub>();
		} else {
			formFilterSelection.clear();
		}

		FormStub allFormsStub = new FormStub();
		allFormsStub.dbId = "0";
		allFormsStub.webId = "0";
		allFormsStub.name = "All Forms";

		formFilterSelection.add(allFormsStub);

		currentlySelectedFormFilter = allFormsStub;

	}

	private void addFormFilters(List<FormStub> formIdNameStubList) {

		for (FormStub stub : formIdNameStubList) {
			formFilterSelection.add(stub);
		}

	}

	private void initializeViewComponents(View rootView) {

		initializeViewPager(rootView);
		initializeActionBarTabs();
		initializeSpinnerTitleBar(rootView);
		initializeMessageView(rootView);
	}

	private void initializeViewPagerFragments() {

		viewFragments = new ArrayList<Fragment>();

		// TODO: move this to the worker fragment later
		List<UserActionListItemInterface> list = DummyDocumentList
				.getDummyDocumentList();

		// @formatter:off
		homeViewFragment = DocumentListViewFragment
				.createInstance("Home", list);
		myWorkViewFragment = DocumentListViewFragment.createInstance("My Work",
				list);
		myDocumentsViewFragment = DocumentListViewFragment.createInstance(
				"My Documents", list);
		starredDocumentsViewFragment = DocumentListViewFragment.createInstance(
				"Starred Documents", list);
		outboxDocumentViewFragment = DocumentListViewFragment.createInstance(
				"Outbox", list);
		// @formatter:on

		viewFragments.add(homeViewFragment);
		viewFragments.add(myWorkViewFragment);
		viewFragments.add(myDocumentsViewFragment);
		viewFragments.add(starredDocumentsViewFragment);
		viewFragments.add(outboxDocumentViewFragment);

	}

	private void initializeTabIcons() {

		ImageView ivHome = new ImageView(getActivity());
		ivHome.setImageResource(R.drawable.homel);

		ImageView ivMyapproval = new ImageView(getActivity());
		ivMyapproval.setImageResource(R.drawable.myapproval);

		ImageView ivMyrequest = new ImageView(getActivity());
		ivMyrequest.setImageResource(R.drawable.myrequestl);

		ImageView ivStarred = new ImageView(getActivity());
		ivStarred.setImageResource(R.drawable.starredl);

		ImageView ivMypending = new ImageView(getActivity());
		ivMypending.setImageResource(R.drawable.mypendingl);

		tabIcons = new ArrayList<ImageView>();

		tabIcons.add(ivHome);
		tabIcons.add(ivMyapproval);
		tabIcons.add(ivMyrequest);
		tabIcons.add(ivStarred);
		tabIcons.add(ivMypending);

	}

	private void initializeActionBarTabs() {

		initializeViewPagerFragments();
		initializeTabIcons();

		abMainActionBar = getActivity().getActionBar();
		abMainActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

		MainTabViewTabListener tabListener = new MainTabViewTabListener();

		for (int i = 0; i < viewFragments.size(); i++) {

			ActionBar.Tab tab = abMainActionBar.newTab();
			tab.setTabListener(tabListener);
			tab.setCustomView(tabIcons.get(i));

			abMainActionBar.addTab(tab);

		}

	}

	private void initializeViewPager(View rootView) {
		vpMainViewPager = (ViewPager) rootView
				.findViewById(R.id.main_vpMainViewPager);
		vpMainViewPager.setAdapter(new MainViewPagerAdapter(
				getFragmentManager()));
		vpMainViewPager
				.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

					@Override
					public void onPageSelected(int index) {
						abMainActionBar.setSelectedNavigationItem(index);
					}

					@Override
					public void onPageScrollStateChanged(int arg0) {
					}

					@Override
					public void onPageScrolled(int arg0, float arg1, int arg2) {
					}
				});
	}

	private void initializeMessageView(View rootView) {
		tvMessage = (TextView) rootView.findViewById(R.id.Main_tvMessage);
		tvMessage.setVisibility(View.GONE);
	}

	private void initializeSpinnerTitleBar(View rootView) {

		// get the default title bar of the view
		int titleBarResourceId = Resources.getSystem().getIdentifier(
				"action_bar_title", "id", "android");
		View titleBarView = getActivity().findViewById(titleBarResourceId);

		// initialize the spinner view that will replace the default title bar
		formfilterAdapter = new ArrayAdapter<FormStub>(getActivity(),
				R.layout.view_form_filter_item, formFilterSelection);
		formfilterAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		spFormFilter = (Spinner) getActivity().getLayoutInflater().inflate(
				R.layout.view_form_filter_spinner, null);

		spFormFilter.setAdapter(formfilterAdapter);

		ViewGroupUtils.replaceView(titleBarView, spFormFilter);

		spFormFilter.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {

				FormStub selectedFilter = formFilterSelection.get(position);

				if (!selectedFilter.dbId
						.equals(currentlySelectedFormFilter.dbId)) {
					currentlySelectedFormFilter = selectedFilter;
					listener.onFormFilterChanged(selectedFilter);
				}

			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
			}

		});

	}

	// ========================================================================
	// Functional Methods

	public void notifyOnlineMode() {
		tvMessage.setText("You are connected to server.");
		tvMessage.setVisibility(View.VISIBLE);
		tvMessage.setBackgroundColor(Color.parseColor("#51d700"));
		tvMessage.postDelayed(new Runnable(){

			@Override
			public void run() {
				tvMessage.setVisibility(View.GONE);		
			}
			
		}, 10000);
	}

	public void notifyOfflineMode() {
		tvMessage.setVisibility(View.VISIBLE);
		tvMessage.setText("You are not connected to server.");	
		tvMessage.setBackgroundColor(Color.parseColor("#eb0000"));
	}

	// ========================================================================
	// Getters & Setters

	public List<FormStub> getFormFilterSelection() {
		return formFilterSelection;
	}

	public void setFormFilterSelection(List<FormStub> newFormFilterSelection) {

		FLLogger.d(TAG, "setting form filter selection");

		// reset the form filter selection, then add the form names
		resetFormFilterSelection();
		addFormFilters(newFormFilterSelection);

		formfilterAdapter.notifyDataSetChanged();
	}

	// ========================================================================
	// Adapters and Event Implementation Private Classes

	private class MainViewPagerAdapter extends FragmentPagerAdapter {

		public MainViewPagerAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public Fragment getItem(int index) {
			return viewFragments.get(index);
		}

		@Override
		public int getCount() {
			return 5;
		}

	}

	private class MainTabViewTabListener implements TabListener {

		@Override
		public void onTabReselected(Tab tab,
				FragmentTransaction fragmentTransaction) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onTabSelected(Tab tab,
				FragmentTransaction fragmentTransaction) {
			vpMainViewPager.setCurrentItem(tab.getPosition());
		}

		@Override
		public void onTabUnselected(Tab tab,
				FragmentTransaction fragmentTransaction) {
			// TODO Auto-generated method stub

		}

	}

	// ========================================================================
	// Interfaces

	public static interface MainViewActivityActionListener {
		public void onFormFilterChanged(FormStub stub);
	}

}
